<?php

namespace App\Http\Controllers\Admin\Setting\Wechat;

use App\Http\Controllers\Admin\Controller;
use App\Services\WeChatOfficialAccountService;
use Illuminate\Http\Request;

class WeChatMenuController extends Controller
{
    public function index(WeChatOfficialAccountService $weChatOfficialAccountService)
    {
        $menus = [];
        $api = $weChatOfficialAccountService->getClient();
        $response = $api->get('/cgi-bin/menu/get');
        if ($response->isSuccessful())
        {
            $data = $response->toArray(true);
            $menus = $data['menu']['button'];
        }
        foreach ($menus as $key => $menu)
        {
            if (isset($menu['sub_button']))
            {
                if (count($menu['sub_button']) > 0)
                {
                    $menus[$key]['subButtons'] = $menu['sub_button'];
                }else{
                    $menus[$key]['subButtons'] = [];
                }

                foreach ($menu['sub_button'] as $subKey => $subMenu)
                {
                    if (isset($subMenu['sub_button']))
                    {
                        unset($menus[$key]['sub_button'][$subKey]['sub_button']);
                    }
                }
                unset($menus[$key]['sub_button']);
            }else{
                $menus[$key]['subButtons'] = [];
            }

        }

        return $this->inertia('setting/wechat/menu/index',[
            'data' => $menus,
        ]);
    }

    public function update(Request $request, WeChatOfficialAccountService $weChatOfficialAccountService)
    {
        $params = $request->all();
        $api = $weChatOfficialAccountService->getClient();
        $response = $api->postJson('/cgi-bin/menu/create',[
            'button' => $params['data'],
        ]);
        if (!$response->isSuccessful())
        {
            abort(403,'微信公众号自定义菜单创建失败');
        }
         return $this->responseSuccess();
    }

}
